/**
 * Created by 功振 on 2016/2/2.
 */
angular.module('Portal').controller('SignUpController',
    function ($rootScope, $scope, $state, $cookies, $interval, userInfoService,md5,$base64,bcrypt ) {

    $scope.signUpInfo = true;

    $scope.phoneNumberRegex = "((13[0-9])|(14[5|7])|(15([0-3]|[5-9]))|(18[0,2,3,5-9]))\\d{8}";
    $scope.idenCodeButtonContent = "获取手机验证码";
    $scope.isIdenCodeDisable = false;

    $scope.usernameReg = '[a-z0-9]([-a-z0-9]*[a-z0-9])?';

    $rootScope.$broadcast('MainClassSet', 'reg_bg');


    $scope.triggerIdentifyingCode = function (phoneNumber) {
        userInfoService.triggerIdentifyingCode(phoneNumber).then(function (response) {
            console.log(response);
            if(response&&response.data&&response.data.code){
                $scope.verifyingCode=response.data.code;
            }
            countDown();
            return response;
        }, function(err) {
            alertify.alert('获取认证码错误', err.data);
        });
    }

    var countDown = function() {
        var timePromise = undefined;
        var second = 60;
        timePromise = $interval(function(){
            if(second <= 0){
                if (timePromise) {
                    $interval.cancel(timePromise);
                    timePromise = undefined;
                    second = 60;
                    $scope.idenCodeButtonContent = "获取手机验证码";
                    $scope.isIdenCodeDisable = false;
                }
            }else{
                $scope.idenCodeButtonContent = second + "秒后可重新获取";
                $scope.isIdenCodeDisable = true;
                second--;
            }
        }, 1000, 100);
    }
    
    $scope.ok = function () {

        if($scope.signUpForm.$valid){
            $scope.signUpInfo = false;
            $scope.isSignUping = true;

            var userInfo = {
                username: $scope.username,
                email: $scope.email,
                password: md5.createHash($scope.password),
                pullSecr:$base64.encode($scope.username+':'+$scope.password),
                role: $scope.role,
                company: $scope.company,
                identifyingCode: $scope.identifyingCode,
                phoneNumber: $scope.phoneNumber
            }
            var salt = bcrypt.genSaltSync(10);
            var bHash = bcrypt.hashSync( $scope.password , salt); //generate bCrypt hash
            if( bHash){
                userInfo["bHash"] = bHash ;
            }

            //创建用户
            userInfoService.createNewUser(userInfo).then(function(response){
                $scope.isSignUping = false;
                $scope.signUpSucceeded = true;
                //$cookies.put("username", $scope.username);
                $cookies.put("hasPhone", "1");
                //window.localStorage.setItem("username", $scope.username);
                //window.localStorage.setItem("hasPhone", "1");
                window.location.href = "/cp";
                //$state.go("cp",{}, {reload:true});
            }, function(error){

                if( !error.status || error.status === -1) {
                    error[status] = null ;
                    //jenkins 服务不可用或者响应时间太长，浏览器会自动失败本次请求
                    error.data = "Request time out !" ;
                }
                console.log("[CreateUserError][status:"+error.status+"]"+JSON.stringify( error.data )) ;

                if( !error.data || error.data ==""){
                    error = {
                        "data":"Failed to create a new User ! "
                    }
                }

                alertify.alert('create user error', error.data);
            });
        }else{
            alertify.alert('create user error', 'some error in submit form');
        }

    };
});